package com.hui.platform.falseworkapi.common.security.jwt;

import com.alibaba.fastjson.JSON;
import com.hui.platform.falseworkapi.common.core.constant.ResultCodeEnum;
import com.hui.platform.falseworkapi.common.core.vo.CommonResult;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 未认证结果处理器（返回401--4001，表示未认证）
 *
 * @author Peng
 * @date 2019/12/5
 */
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -8970718410437077606L;

    private final transient MessageSource messageSource;

    public JsonAuthenticationEntryPoint(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        // This is invoked when user tries to access a secured REST resource without supplying any credentials
        // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to

        //响应请求
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //设置跨域
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Origin","*");
        //设置响应码401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        //包装数据
        CommonResult<String> unauthorized = CommonResult.build(ResultCodeEnum.UNAUTHORIZED, messageSource, null, authException.getMessage());
        response.getWriter().println(JSON.toJSONString(unauthorized));
        response.getWriter().flush();
    }
}